import numpy as np
from collections import Counter
class KNN:
    def __init__(self, k: int = 3):
        self.k = k
    def fit(self, X: np.ndarray, y: np.ndarray):
        """ 存储训练数据 """
        self.X_train = X
        self.y_train = y
    def predict(self, X: np.ndarray) -> np.ndarray:
        """ 对新数据进行预测 """
        predictions = [self._predict(x) for x in X]
        return np.array(predictions)
    def _predict(self, x: np.ndarray) -> object:
        """ 预测单个样本的类别 """
        # 计算距离
        distances = [np.sqrt(np.sum((x - x_train)**2)) for x_train in self.X_train]
        # 找到k个最近邻居的索引
        k_indices = np.argsort(distances)[:self.k]
        # 提取k个最近邻居的标签
        k_nearest_labels = [self.y_train[i] for i in k_indices]
        # 最常见的标签
        most_common = Counter(k_nearest_labels).most_common(1)
        return most_common[0][0]
# 示例数据集
X_train = np.array([
    [1, 2], [2, 3], [3, 1.5], [4, 3], [5, 4], [6, 2.5], [7, 5],
    [8, 6], [9, 4.5], [10, 5]
])
y_train = np.array(['A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C'])
# 创建KNN实例
knn = KNN(k=3)
# 训练模型（这里只是存储数据）
knn.fit(X_train, y_train)
# 测试数据
X_test = np.array([
    [2.5, 2], 
    [6.5, 5], 
    [9, 3]
])
# 预测
predictions = knn.predict(X_test)
# 输出结果
for i, prediction in enumerate(predictions):
    print(f"点 {X_test[i]} 的预测类别是 {prediction}")
